﻿CREATE PROCEDURE [Mapping].[AddMapping]
  @groupId int,
	@sourceKey Mapping.SourceKeyTable READONLY,
	@targetKeyId int,
  @priority int = NULL,
	@masked bit = 0,
	@enabled bit = 1,
	@description nvarchar(200) = NULL
AS
  BEGIN TRY
	  BEGIN TRAN

    IF @priority IS NULL
      SELECT @priority = MAX([Priority]) + 1 FROM Mapping.MappingItem WHERE [Group] = @groupId

	  DECLARE @mappingItemId int
    INSERT INTO Mapping.MappingItem([Group], TargetKey, [Priority], [Masked], [Enabled], [Description])
      VALUES(@groupId, @targetKeyId, @priority, @masked, @enabled, @description)

    SET @mappingItemId = @@IDENTITY

    INSERT INTO Mapping.SourceKey([MappingItem], [KeyColumn], [KeyValue]) 
      SELECT @mappingItemId, [KeyColumn], [KeyValue] FROM @sourceKey

    COMMIT
  END TRY
  BEGIN CATCH
    IF @@TRANCOUNT > 0 ROLLBACK
	END CATCH

RETURN @mappingItemId
